import { SetupContext, Ref, ref, onMounted, nextTick, onUnmounted, watch } from 'vue';
import { ExtendPanelPropsType } from '../extend-panel.props'
import { UseDomChange } from './types';
export function useDomChange(
    props: ExtendPanelPropsType,
    context: SetupContext,
    extendPanelRef: Ref
): UseDomChange {
    let coverWidth = ref<number | string>('100%');
    let contentWidth = ref<string>('');
    let resizeObserver: ResizeObserver;
    let isInit = ref<boolean>(true);
    const setWidth = () => {
        if (!extendPanelRef.value) return;
        let extendPanelWidth = extendPanelRef.value.clientWidth;
        let items = [...extendPanelRef.value?.children[0]?.children]
        let retractItems: any = items.map((el: Element) => {
            return {
                width: el.clientWidth,
                el: el
            }
        });
        let minItem = retractItems.sort((a: any, b: any) => a.width - b.width)[0];
        if(!minItem) return;
        let noCheckedWidth = minItem.width;
        coverWidth.value = noCheckedWidth;
        contentWidth.value = (extendPanelWidth - noCheckedWidth) + 'px';
    }
    const styleVariableItemWidth = () => {
        resizeObserver = new ResizeObserver(() => {
            if (!isInit.value) setWidth();
            isInit.value = false;
        });
        if (!extendPanelRef.value) return;
        resizeObserver.observe(extendPanelRef.value);
    }
    watch(props.data, () => {
        nextTick(() => {
            setWidth();
        })
    })
    onMounted(() => {
        nextTick(() => {
            setWidth();
            styleVariableItemWidth();
        })
    })
    onUnmounted(() => {
        resizeObserver.disconnect()
    })
    return {
        coverWidth,
        contentWidth
    }
}